package com.hengyi.webcrawler.processor;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.hengyi.webcrawler.entity.Match;
import com.hengyi.webcrawler.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Author:  dongzp
 * Time:    2019/11/05 9:38
 * Project: web-crawler
 * Email:   90fanhua@gmail.com
 * Remarks: 北单赛前胜平负体彩数据分析
 **/
@Slf4j
@Component
public class BeidanPreMatchSpfPageProcessor implements PageProcessor {

    private String GOOGLE_USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36";

    private Site site = Site.me().setRetryTimes(3).setSleepTime(3000).setTimeOut(10000).setCharset("UTF-8").setUserAgent(GOOGLE_USER_AGENT);

    @Override
    public void process(Page page) {
        String issue = CommonUtils.parseIssue(page.getRequest().getUrl());
        List<Match> matchList = new ArrayList<>();
        Selectable select = page.getHtml().$("tbody tr");
        List<Selectable> nodes = select.nodes();
        Selectable selectable;
        Match match = null;
        for(int i = 1;i < nodes.size();i++){
            selectable = nodes.get(i);
            match = new Match();
            // 取状态
            String sellStatusStr = selectable.css("tr","name1").get();
            Integer sellStatus = CommonUtils.getStatus(sellStatusStr);
            match.setSellStatus(sellStatus);
            // 比赛名称
            String league = selectable.css("tr","name2").get();
            match.setLeague(league);
            // 比赛时间
            String matchTime = selectable.css("tr","title").get();
            if(StringUtils.isBlank(matchTime)){
                continue;
            }
            Date mTime = DateUtil.parse(matchTime,"yyyy-MM-dd HH:mm:ss");
            match.setMatchTime(mTime);
            match.setMatchTimestamp(mTime.getTime());
            // 编号
            String issueNum = selectable.css("tr","id").get().replace("tr_","");
            match.setIssueNum(Integer.parseInt(issueNum));
            match.setIssue(Integer.parseInt(issue));
            // 设置日期
            CommonUtils.setDate(page.getRequest().getUrl(),match);
            // 主队
            String home = selectable.$("tr td:nth-child(5)","text").get();
            match.setHome(home.trim());
            // 客队
            String away = selectable.$("tr td:nth-child(7)","text").get();
            match.setAway(away.trim());
            // 让球
            String rq = selectable.$("tr td.bgRq","text").get();
            match.setRq(rq);
            // 胜平负
            List<String> spfList = selectable.$("tr td[name='td'] label span","text").all();
            if(sellStatus == 1){
                JSONObject spfJson = new JSONObject();
                spfJson.put("s",spfList.get(0));
                spfJson.put("p",spfList.get(1));
                spfJson.put("f",spfList.get(2));
                spfJson.put("updateTime",System.currentTimeMillis());
                match.setSpf(spfJson.toJSONString());
            } else if (sellStatus == 4) {
                int index = 0;
                for(String spf : spfList){
                    if(!spf.trim().equals("0")){
                        if(index == 0){
                            match.setSpfResult("3");
                        } else if (index == 1) {
                            match.setSpfResult("1");
                        }else {
                            match.setSpfResult("0");
                        }
                        break;
                    }
                    index++;
                }
            }

            matchList.add(match);
        }
        page.putField("match",matchList);
        log.info("北单赛前胜平负数据爬取成功，数量：{}",matchList.size());
    }

    @Override
    public Site getSite() {
        return site;
    }
}
